﻿using BootstrapBlazor.Components;
using Microsoft.Win32;
using LaserMark.Components.Components;
using LaserMark.Components.Events;
using LaserMark.Extensions;
using LaserMark.Models;
using LaserMark.Components.Utils;
using LaserMark.Control.Service;
using LaserMark.DataAccess.Models;
using LaserMark.View.Services;
using System.Diagnostics;
using System.IO;
using System.Timers;
using System.Windows.Documents;

namespace LaserMark.Components.Pages
{
    public partial class Home
    {
        private bool IsShow { get; set; } = true;


        protected override void OnRegisterEvent()
        {
            base.OnRegisterEvent();
            var zeroBackEvent = new RibbonTabEvent(RibbonTabConstants.ZeroBack, async item =>
            {
                if (!GlobalStatus.IsEmergencyStop)
                {
                    _ = Task.Run(async () =>
                    {
                        await Control.GetAxisStatus(0, (short)MarkOption.AxisCode.X, out int servo, 1, out _);
                        if ((servo & 0x200) != 0)
                        {
                            var pluse = MarkOption.ZeroOffSet.X / MarkOption.XPluse.Value;
                            var ret = GoHomeExtension.Go((short)MarkOption.AxisCode.X, (int)pluse, -((int)MarkOption.ZeroVel.X), ((int)MarkOption.ZeroVel.X), MarkOption.ZeroAcc.X / 10000, MarkOption.ZeroDec.X / 10000);
                            if (ret)
                            {
                                GlobalStatus.IsXZeroBack = true;
                            }
                        }
                    });

                    _ = Task.Run(async () =>
                    {
                        await Control.GetAxisStatus(0, (short)MarkOption.AxisCode.Y, out int servo, 1, out _);
                        if ((servo & 0x200) != 0)
                        {
                            var pluse = MarkOption.ZeroOffSet.Y / MarkOption.YPluse.Value;
                            var ret = GoHomeExtension.Go((short)MarkOption.AxisCode.Y, (int)pluse, -((int)MarkOption.ZeroVel.Y), ((int)MarkOption.ZeroVel.Y), MarkOption.ZeroAcc.Y / 10000, MarkOption.ZeroDec.Y / 10000);
                            if (ret)
                            {
                                GlobalStatus.IsYZeroBack = true;
                            }
                        }
                    });

                    _ = Task.Run(async () =>
                    {
                        await Control.GetAxisStatus(0, (short)MarkOption.AxisCode.Z, out int servo, 1, out _);
                        if ((servo & 0x200) != 0)
                        {
                            var pluse = MarkOption.ZeroOffSet.Z / MarkOption.ZPluse.Value;
                            var ret = GoHomeExtension.Go((short)MarkOption.AxisCode.Z, (int)pluse, -((int)MarkOption.ZeroVel.Z), ((int)MarkOption.ZeroVel.Z), MarkOption.ZeroAcc.Z / 10000, MarkOption.ZeroDec.Z / 10000);
                            if (ret)
                            {
                                GlobalStatus.IsZZeroBack = true;
                            }
                        }
                    });
                }
                else
                {
                    await ToastService.Error("提示", "当前处于急停状态");
                }
            });
            var autoOrManualEvent = new RibbonTabEvent(RibbonTabConstants.AutoOrManual, item =>
            {
                if (item.TabItem.Text == "自动")
                {
                    item.TabItem.Icon = "fa-solid fa-m";
                    item.TabItem.Text = "手动";
                }
                else
                {
                    item.TabItem.Icon = "fa-solid fa-a";
                    item.TabItem.Text = "自动";
                }

                StateHasChanged();
                return Task.CompletedTask;
            });

            var openFileBackEvent = new RibbonTabEvent(RibbonTabConstants.OpenFile, async item =>
            {
                if (Info.OriginalCount != 0)
                {
                    var ret = await SwalService.ShowModal(new SwalOption()
                    {
                        Category = SwalCategory.Error,
                        IsConfirm = true,
                        Content = "当前已加载有订单信息，是否要切换"
                    });

                    if (ret)
                    {
                        var res = openDialog();

                        if (res)
                        {
                            Fifo1MarkRestEvent.Close();
                            MarkRestEvent.Close();
                            PauseRestEvent.Close();
                            PauseSource.Cancel();
                            FinishToken.Cancel();
                            CurrentOriginalIndex = 0;
                            CurrentPieceIndex = 0;
                            Count = 0;

                            Fifo1MarkRestEvent = new(true);
                            MarkRestEvent = new(true);
                            PauseRestEvent = new(true);
                            PauseSource = new();
                            FinishToken = new();

                            await Control.SetDoBit(0, mc.MC_GPO, 3, 1);
                            await Control.SetDoBit(0, mc.MC_GPO, 4, 1);

                            Items.Clear();
                            GlobalStatus.ProductMessage = "";
                            if (Info.Originals != null && Info.Originals.Count != 0)
                            {
                                CurrentOriginal = Info.Originals.First();
                                CurrentOriginalIndex = 1;
                                var i = 0;
                                foreach (var original in Info.Originals)
                                {
                                    ++i;
                                    Items.Add(new Template()
                                    {
                                        Id = i.ToString(),
                                        Specification = $"{original.Width} * {original.Height}",
                                        VersionOrder = i,
                                        SliceOrder = original.Price,
                                        MaterialQuality = original.MaterialQuality
                                    });
                                }
                                Content = SvgBuilderExtension.Create(CurrentOriginal);
                                await SvgEditor.UpdateAsync(Content);
                            }
                            StateHasChanged();
                        }
                    }
                }
                else
                {
                    openDialog();
                    GlobalStatus.ProductMessage = "";
                    Items.Clear();
                    if (Info.Originals != null && Info.Originals.Count != 0)
                    {
                        CurrentOriginal = Info.Originals.First();
                        CurrentOriginalIndex = 1;
                        var i = 0;
                        foreach (var original in Info.Originals)
                        {
                            ++i;
                            Items.Add(new Template()
                            {
                                Id = i.ToString(),
                                Specification = $"{original.Width} * {original.Height}",
                                VersionOrder = i,
                                SliceOrder = original.Price,
                                MaterialQuality = original.MaterialQuality
                            });
                        }
                        Content = SvgBuilderExtension.Create(CurrentOriginal);
                        await SvgEditor.UpdateAsync(Content);
                    }
                    StateHasChanged();
                }
            });

            var selectTemplateEvent = new RibbonTabEvent(RibbonTabConstants.SelectTemplate, async item =>
            {
                var option = new DialogOption()
                {
                    Title = "上传模板",
                    Size = Size.ExtraLarge,
                    BodyTemplate = BootstrapDynamicComponent.CreateComponent<UploadCodeTemp>().Render(),
                    ShowFooter = false
                };

                await DialogService.Show(option);
            });

            var systemSettingskEvent = new RibbonTabEvent(RibbonTabConstants.SystemSettings, async item =>
            {
                await DialogService!.Show(new DialogOption()
                {
                    Size = Size.ExtraLarge,
                    Title = "参数配置",
                    Class = "settings",
                    ShowFooter = false,
                    IsDraggable = true,
                    BodyTemplate = BootstrapDynamicComponent.CreateComponent<Settings>().Render()
                });
            });

            var taskListEvent = new RibbonTabEvent(RibbonTabConstants.TaskList, async item =>
            {
                if (IsAutoReadTask)
                {
                    item.TabItem.Text = "单机";
                    item.TabItem.Icon = "fa-solid fa-globe";
                    IsAutoReadTask = !IsAutoReadTask;
                    StateHasChanged();
                }
                else
                {
                    if (!Directory.Exists(MarkOption.AutoFolder.Value!))
                    {
                        await ToastService.Error("提示", "联机任务夹不存在!");
                    }
                    else
                    {
                        IsAutoReadTask = !IsAutoReadTask;
                        item.TabItem.Text = "联机";
                        item.TabItem.Icon = "fa-solid fa-network-wired";
                        AutoTaskTimer = new System.Timers.Timer(1000);
                        AutoTaskTimer.Elapsed += Timer_Elapsed1;
                        AutoTaskTimer.Start();
                    }
                    StateHasChanged();
                }
            });

            #region 新建版面、修改版面
            var newTemplateEvent = new RibbonTabEvent(RibbonTabConstants.NewTemplate, async item =>
            {
                IsShow = !IsShow;
                await DialogService!.Show(new DialogOption()
                {
                    Title = "新建版面",
                    Class = "new-template",
                    BodyTemplate = BootstrapDynamicComponent.CreateComponent<SvgEditor>().Render(),
                    ShowFooter = false,
                    OnCloseAsync = new Func<Task>(() =>
                    {
                        IsShow = !IsShow;
                        StateHasChanged();
                        return Task.CompletedTask;
                    })
                });
                StateHasChanged();
            });

            var updateTemplateEvent = new RibbonTabEvent(RibbonTabConstants.UpdaeteTemplate, async item =>
            {
                IsShow = !IsShow;
                await DialogService!.Show(new DialogOption()
                {
                    Title = "修改版面",
                    Class = "new-template",
                    BodyTemplate = BootstrapDynamicComponent.CreateComponent<SvgEditor>(new Dictionary<string, object?>
                    {
                        [nameof(SvgEditor.PreContent)] = Content,
                        [nameof(SvgEditor.OnSaveChanged)] = new Func<string?, Task>(s =>
                        {
                            Content = s;
                            return Task.CompletedTask;
                        })
                    }).Render(),
                    ShowFooter = false,
                    OnCloseAsync = new Func<Task>(() =>
                    {
                        IsShow = !IsShow;
                        StateHasChanged();
                        return Task.CompletedTask;
                    })
                });
                StateHasChanged();
            });
            #endregion

            var auditLogEvent = new RibbonTabEvent(RibbonTabConstants.AuditLog, async item =>
            {
                await DialogService!.Show(new DialogOption()
                {
                    Size = Size.ExtraLarge,
                    Title = "操作日志",
                    Class = "new-template",
                    BodyTemplate = BootstrapDynamicComponent.CreateComponent<ActionLog>().Render(),
                    ShowFooter = false,
                });
                StateHasChanged();
            });

            var ezd3Event = new RibbonTabEvent(RibbonTabConstants.Ezd3, item =>
            {
                Process process = new Process();
                var info = new ProcessStartInfo();
                info.FileName = "Ezcad3";
                info.WorkingDirectory = $"{AppContext.BaseDirectory}";
                process.StartInfo = info;
                process.Start();
                return Task.CompletedTask;
            });

            var runEvent = new RibbonTabEvent(RibbonTabConstants.Run, async item =>
            {
                if (GlobalStatus.IsEmergencyStop)
                {

                }
                else
                {
                    if (GlobalStatus.IsXZeroBack && GlobalStatus.IsYZeroBack && GlobalStatus.IsYZeroBack)
                    {
                        if (GlobalStatus.IsPause)
                        {
                            PauseRestEvent.Set();
                            PauseSource = new();
                            GlobalStatus.IsPause = false;
                            mc.GT_CrdStart(0, 1, 0);
                            await Control.SetDoBit(0, mc.MC_GPO, 4, 0);
                            await Control.SetDoBit(0, mc.MC_GPO, 3, 1);

                            _ = Task.Run(async () =>
                            {
                                var isComplete = await CheckStatus(true);
                                if (isComplete && !GlobalStatus.IsPause)
                                {
                                    await InvokeAsync(async () =>
                                    {
                                        await CrdStop();
                                        StateHasChanged();
                                    });

                                    GlobalStatus.IsMarked = false;
                                    await Control.SetDoBit(0, mc.MC_GPO, 4, 1);
                                    await Control.SetDoBit(0, mc.MC_GPO, 3, 0);
                                    await Control.SetDoBit(0, mc.MC_GPO, 11, 0);
                                    PauseSource.Cancel();
                                }
                            });
                        }
                        else if (GlobalStatus.IsStop)
                        {
                            FinishToken = new();
                            GlobalStatus.IsStop = false;
                            var trap = new mc.TTrapPrm();
                            trap.acc = 0.1;
                            trap.dec = 0.1;
                            trap.smoothTime = 49;
                            await Control.SetPTP(0, (short)MarkOption.AxisCode.X, 100, 0, ref trap);
                            await Control.SetPTP(0, (short)MarkOption.AxisCode.Z, 15, 0, ref trap);
                            int status1;
                            do
                            {
                                await Task.Delay(10);
                                mc.GT_GetSts(0, (short)MarkOption.AxisCode.X, out status1, 1, out _);
                                await Task.Delay(300);
                            } while ((status1 & 0x400) != 0);
                            int status2;
                            do
                            {
                                await Task.Delay(10);
                                mc.GT_GetSts(0, (short)MarkOption.AxisCode.Y, out status2, 1, out _);
                            } while ((status2 & 0x400) != 0);
                            int status3;
                            do
                            {
                                await Task.Delay(10);
                                mc.GT_GetSts(0, (short)MarkOption.AxisCode.X, out status3, 1, out _);
                            } while ((status3 & 0x400) != 0);

                            await Mark();
                        }
                        else
                        {
                            await Mark();
                        }
                    }
                    else
                    {
                        await ToastService.Warning("提示", "请先进行机械回零");
                    }
                }
            });

            var stopEvent = new RibbonTabEvent(RibbonTabConstants.Stop, async item =>
            {
                await Stop();
            });

            var pauseEvent = new RibbonTabEvent(RibbonTabConstants.Pause, async item =>
            {
                if (!GlobalStatus.IsPause)
                {
                    PauseSource.Cancel();
                    await Control.Stop(0, 1 << 8, 0);
                    PauseRestEvent.Reset();
                    GlobalStatus.IsPause = true;
                    await Control.SetDoBit(0, mc.MC_GPO, 3, 0);
                    await Control.SetDoBit(0, mc.MC_GPO, 4, 1);
                    mc.GT_CrdStatus(0, 1, out _, out int segment, 0);
                    PauseSegment = segment;
                }
            });

            var clearStsEvent = new RibbonTabEvent(RibbonTabConstants.ClearSts, async item =>
            {
                await Control.ClearAxisStatus(0, (short)MarkOption.AxisCode.X, 1);
                await Control.ClearAxisStatus(0, (short)MarkOption.AxisCode.Y, 1);
                await Control.ClearAxisStatus(0, (short)MarkOption.AxisCode.Z, 1);

                mc.GT_SetDoBit(0, mc.MC_GPO, 1, 0);
                await Control.SetDoBit(0, mc.MC_GPO, 2, 1);
                GlobalStatus.IsEmergencyStop = false;
                GlobalStatus.Iscan = false;
                GlobalStatus.ScanMesaage = "";
            });

            var onKeepEvent = new RibbonTabEvent(RibbonTabConstants.OnKeep, async item =>
            {
                if (Continuous)
                {
                    Continuous = !Continuous;
                    item.TabItem.Text = "单次";
                    item.TabItem.Icon = "fa-solid fa-1";
                    await Control.SetDoBit(0, mc.MC_GPO, 4, 1);
                }
                else
                {
                    Continuous = !Continuous;
                    item.TabItem.Text = "连打";
                    item.TabItem.Icon = "fa-solid fa-arrows-spin";
                    await Control.SetDoBit(0, mc.MC_GPO, 4, 1);
                }
            });

            var transforEvent = new RibbonTabEvent(RibbonTabConstants.OnlyTransfor, async item =>
            {
                if (GlobalStatus.IsOnlyTransfor)
                {
                    item.TabItem.IsActive = !item.TabItem.IsActive;
                    GlobalStatus.IsOnlyTransfor = false;
                    await Control.SetDoBit(0, mc.MC_GPO, 11, 1);
                }
                else
                {
                    item.TabItem.IsActive = !item.TabItem.IsActive;
                    GlobalStatus.IsOnlyTransfor = true;
                    await Control.SetDoBit(0, mc.MC_GPO, 11, 0);
                }
                StateHasChanged();
            });

            var openFiles = new RibbonTabEvent(RibbonTabConstants.OpenFiles, async item =>
            {
                try
                {
                    var dialog = new OpenFolderDialog();
                    dialog.Title = "请选择文件夹";
                    dialog.InitialDirectory = $@"{AppContext.BaseDirectory}";

                    var result = dialog.ShowDialog();
                    if (result!.Value == true)
                    {
                        var files = Directory.EnumerateFiles(dialog.FolderName, "*.g", SearchOption.AllDirectories);
                        Info.FileName = dialog.SafeFolderName;
                        foreach (var path in files)
                        {
                            Info.Originals.Add(GCode.Read(path, MarkOption.GCodeOrder));
                        }
                        Info.OriginalCount = files.Count();

                        Items.Clear();
                        GlobalStatus.ProductMessage = "";
                        if (Info.Originals != null && Info.Originals.Count != 0)
                        {
                            CurrentOriginal = Info.Originals.First();
                            CurrentOriginalIndex = 1;
                            var i = 0;
                            foreach (var original in Info.Originals)
                            {
                                ++i;
                                Items.Add(new Template()
                                {
                                    Id = i.ToString(),
                                    Specification = $"{original.Width} * {original.Height}",
                                    VersionOrder = i,
                                    SliceOrder = original.Price,
                                    MaterialQuality = original.MaterialQuality
                                });
                            }
                            Content = SvgBuilderExtension.Create(CurrentOriginal);
                            await SvgEditor.UpdateAsync(Content);
                        }
                        StateHasChanged();
                    }
                    else
                    {
                    }
                }
                catch (Exception)
                {
                }
            });

            Events.AddRange(new List<RibbonTabEvent>()
            {
                zeroBackEvent,
                autoOrManualEvent,
                openFileBackEvent,
                systemSettingskEvent,
                selectTemplateEvent,
                taskListEvent,
                newTemplateEvent,
                updateTemplateEvent,
                auditLogEvent,
                ezd3Event,
                runEvent,
                stopEvent,
                clearStsEvent,
                pauseEvent,
                onKeepEvent,
                transforEvent,
                openFiles
            });

            EventBus.RegisterHandler(selectTemplateEvent);
            EventBus.RegisterHandler(openFileBackEvent);
            EventBus.RegisterHandler(zeroBackEvent);
            EventBus.RegisterHandler(autoOrManualEvent);
            EventBus.RegisterHandler(systemSettingskEvent);
            EventBus.RegisterHandler(taskListEvent);
            EventBus.RegisterHandler(newTemplateEvent);
            EventBus.RegisterHandler(updateTemplateEvent);
            EventBus.RegisterHandler(auditLogEvent);
            EventBus.RegisterHandler(ezd3Event);
            EventBus.RegisterHandler(runEvent);
            EventBus.RegisterHandler(stopEvent);
            EventBus.RegisterHandler(clearStsEvent);
            EventBus.RegisterHandler(pauseEvent);
            EventBus.RegisterHandler(onKeepEvent);
            EventBus.RegisterHandler(transforEvent);
            EventBus.RegisterHandler(openFiles);
        }

        private async void Timer_Elapsed1(object? sender, ElapsedEventArgs e)
        {
            if (CurrentOriginalIndex >= Info.OriginalCount)
            {
                DirectoryInfo directory = new DirectoryInfo(MarkOption.AutoFolder.Value!);
                var files = directory.GetFiles("*.g");
                if (files.Count() > 0 && !IsAutoTask)
                {
                    IsAutoTask = true;
                    Info.Originals.Add(GCode.Read(files[0].FullName, MarkOption.GCodeOrder));
                    Info.FileName = files[0].Name;
                    Info.OriginalCount = 1;
                    CurrentPieceIndex = 0;
                    CurrentOriginalIndex = 1;
                    CurrentOriginal = Info.Originals.First();

                    var i = 0;
                    foreach (var original in Info.Originals)
                    {
                        ++i;
                        Items.Add(new Template()
                        {
                            Id = i.ToString(),
                            Specification = $"{original.Width} * {original.Height}",
                            VersionOrder = i,
                            SliceOrder = original.Price,
                            MaterialQuality = original.MaterialQuality
                        });
                    }

                    Content = SvgBuilderExtension.Create(CurrentOriginal);
                    await SvgEditor.UpdateAsync(Content);
                    AutoTaskTimer.Stop();
                    IsAutoTask = false;
                    await InvokeAsync(async () =>
                    {
                        await Table.QueryAsync();
                    });

                    File.Delete(files[0].FullName);
                }
            }
        }

        private bool openDialog()
        {

            SynchronizationContext.Current!.Post(_ =>
            {
                try
                {
                    var dialog = new OpenFileDialog();
                    dialog.Title = "请选择解析文件";
                    dialog.InitialDirectory = $@"{AppContext.BaseDirectory}";
                    dialog.Filter = "g文件|*.g|opt文件|*.opt|压缩文件|*.zip";

                    var result = dialog.ShowDialog();
                    if (result!.Value == true)
                    {
                        Info = ResolveFileExtension.Resolve(dialog, MarkOption);
                    }
                    else
                    {
                    }
                }
                catch (Exception)
                {
                }
            }, null);

            return true;
        }

        private async Task CrdStop()
        {
            CurrentPieceIndex += 1;
            var item = Items.ElementAt(CurrentOriginalIndex - 1);
            if (CurrentPieceIndex >= item.SliceOrder)
            {
                CurrentOriginalIndex += 1;
                if (CurrentOriginalIndex <= Info.OriginalCount)
                {
                    item.Status = Status.Printed;
                    var count = 0;
                    while (Items[CurrentOriginalIndex - 1 + count].Status == Status.Printed)
                    {
                        count++;
                    }
                    CurrentPieceIndex = 0;
                    CurrentOriginal = Info.Originals[CurrentOriginalIndex - 1 + count];
                    CurrentOriginalIndex = CurrentOriginalIndex + count;
                    Content = SvgBuilderExtension.Create(CurrentOriginal);
                    await SvgEditor.UpdateAsync(Content);
                }
                else
                {
                    item.Status = Status.Printed;
                    if (Items.Any(s => s.Status != Status.NoPrint && s.Status != Status.Printting))
                    {
                        CurrentOriginalIndex = CurrentOriginalIndex - 1;
                        await Control.SetDoBit(0, mc.MC_GPO, 4, 1);

                        if (IsAutoReadTask)
                        {
                            AutoTaskTimer.Start();
                        }
                    }
                }

                if (Items.Any(s => s.Status != Status.NoPrint && s.Status != Status.Printting))
                {
                    await Control.SetDoBit(0, mc.MC_GPO, 6, 0);
                }
            }
            else
            {
            }

            var ttr = new mc.TTrapPrm();
            ttr.acc = 0.1;
            ttr.dec = 0.1;
            ttr.smoothTime = 49;
            await Control.SetPTP(0, (short)MarkOption.AxisCode.Z, 10, 0, ref ttr);
            await Print.Dispose();
            await InvokeAsync(StateHasChanged);
        }

        private async Task Mark()
        {
            if (Info.OriginalCount == 0)
            {
                GlobalStatus.ProductMessage = "当前未加载订单信息";
            }
            else if (!Items.Any(s => s.Status == Status.NoPrint || s.Status == Status.Printting))
            {
                GlobalStatus.ProductMessage = "当前订单已完成";
            }
            else
            {
                if (Continuous)
                {
                    PauseSource = new();
                    GlobalStatus.StopToken = new();
                    _ = Task.Factory.StartNew(async e =>
                    {
                        await Control.SetDoBit(0, mc.MC_GPO, 4, 0);
                        await Control.SetDoBit(0, mc.MC_GPO, 3, 1);
                        while (GlobalStatus.StopToken.Token is { IsCancellationRequested: false })
                        {
                            if (!GlobalStatus.StopToken.IsCancellationRequested)
                            {
                                await Task.Delay(100);
                                await Control.GetDi(0, mc.MC_GPI, out int value);
                                var status = Convert.ToString(value, 2).PadLeft(16, '0');
                                if (status[4] == '1' && !GlobalStatus.IsMarked && GlobalStatus.IsTransComplete)
                                {
                                    GlobalStatus.IsTransComplete = false;
                                    if (CurrentOriginalIndex <= Info.OriginalCount)
                                    {
                                        if (PauseRestEvent.WaitOne() && !PauseSource.IsCancellationRequested && !GlobalStatus.IsMarked)
                                        {
                                            if (MarkOption.MarkArgs.IsAutoMark)
                                            {
                                                _ = Task.Run(async () =>
                                                {
                                                    await Print.CreateEntMgrAsync();
                                                });
                                            }

                                            GlobalStatus.IsMarked = true;
                                            if (MarkOption.PhotoelectricitySetting.ScanType == "0")
                                            {
                                                var ret = await ScanPointExtension.Scan((int)CurrentOriginal.Width, (int)CurrentOriginal.Height, MarkOption, Control, FinishToken);
                                                if (ret.Item7)
                                                {
                                                    var x = ret.Item2;
                                                    var y = ret.Item3;
                                                    Items.ElementAt(CurrentOriginalIndex - 1).Status = Status.Printting;
                                                    CurrentOriginalIndex = Info.Originals.IndexOf(CurrentOriginal) + 1;
                                                    await InvokeAsync(async () =>
                                                    {
                                                        await Table.QueryAsync();
                                                    });
                                                    await CreateCardEx.Create(CurrentOriginal, MarkOption, PauseRestEvent, x, y, degress: ret.Item6);
                                                    var isComplete = await CheckStatus();
                                                    if (isComplete && !GlobalStatus.IsPause)
                                                    {
                                                        GlobalStatus.IsMarked = false;
                                                        await InvokeAsync(async () =>
                                                        {
                                                            await CrdStop();
                                                            StateHasChanged();
                                                        });
                                                        await Control.SetDoBit(0, mc.MC_GPO, 11, 0);
                                                    }
                                                }
                                                else
                                                {
                                                    await Control.SetDoBit(0, mc.MC_GPO, 2, 0);
                                                    GlobalStatus.Iscan = true;
                                                    GlobalStatus.ScanMesaage = ret.Item1;
                                                    GlobalStatus.IsXZeroBack = false;
                                                    GlobalStatus.IsYZeroBack = false;
                                                    GlobalStatus.IsZZeroBack = false;
                                                    GlobalStatus.IsEmergencyStop = true;
                                                    await Stop();
                                                }
                                            }
                                            else
                                            {
                                                Items.ElementAt(CurrentOriginalIndex - 1).Status = Status.Printting;
                                                CurrentOriginalIndex = Info.Originals.IndexOf(CurrentOriginal) + 1;
                                                await InvokeAsync(async () =>
                                                {
                                                    await Table.QueryAsync();
                                                });
                                                await CreateCardEx.Create(CurrentOriginal, MarkOption, PauseRestEvent, MarkOption.PhotoelectricitySetting.Height1 / MarkOption.XPluse.Value, MarkOption.PhotoelectricitySetting.Height2 / MarkOption.YPluse.Value);
                                                var isComplete = await CheckStatus();
                                                if (isComplete && !GlobalStatus.IsPause)
                                                {
                                                    GlobalStatus.IsMarked = false;
                                                    await InvokeAsync(async () =>
                                                    {
                                                        await CrdStop();
                                                        StateHasChanged();
                                                    });
                                                    await Control.SetDoBit(0, mc.MC_GPO, 11, 0);
                                                }

                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }, TaskCreationOptions.LongRunning, GlobalStatus.StopToken.Token);
                }
                else
                {
                    await Control.GetDi(0, mc.MC_GPI, out int value);
                    var status = Convert.ToString(value, 2).PadLeft(16, '0');
                    if (status[4] == '1')
                    {
                        await Control.SetDoBit(0, mc.MC_GPO, 4, 0);
                        //检查上个打标动作是否完成
                        if (!GlobalStatus.IsMarked)
                        {
                            GlobalStatus.IsTransComplete = false;
                            if (MarkOption.MarkArgs.IsAutoMark)
                            {
                                _ = Task.Run(async () =>
                                {
                                    await Print.CreateEntMgrAsync();
                                });
                            }
                            PauseSource = new();
                            GlobalStatus.IsMarked = true;
                            _ = Task.Factory.StartNew(async e =>
                            {
                                while (PauseSource is { IsCancellationRequested: false } && !FinishToken.IsCancellationRequested)
                                {
                                    if (CurrentOriginalIndex <= Info.OriginalCount)
                                    {
                                        if (PauseRestEvent.WaitOne())
                                        {
                                            if (MarkOption.PhotoelectricitySetting.ScanType == "0")
                                            {
                                                var ret = await ScanPointExtension.Scan((int)CurrentOriginal.Width, (int)CurrentOriginal.Height, MarkOption, Control, FinishToken);
                                                if (ret.Item7)
                                                {
                                                    var x = ret.Item2;
                                                    var y = ret.Item3;
                                                    Items.ElementAt(CurrentOriginalIndex - 1).Status = Status.Printting;
                                                    CurrentOriginalIndex = Info.Originals.IndexOf(CurrentOriginal) + 1;
                                                    await InvokeAsync(async () =>
                                                    {
                                                        await Table.QueryAsync();
                                                    });
                                                    await CreateCardEx.Create(CurrentOriginal, MarkOption, PauseRestEvent, x, y, degress: ret.Item6);
                                                    var isComplete = await CheckStatus(true);
                                                    if (isComplete && !GlobalStatus.IsPause)
                                                    {
                                                        GlobalStatus.IsMarked = false;
                                                        PauseSource.Cancel();
                                                        await InvokeAsync(async () =>
                                                        {
                                                            await CrdStop();
                                                            StateHasChanged();
                                                        });
                                                        await Control.SetDoBit(0, mc.MC_GPO, 11, 0);
                                                    }
                                                }
                                                else
                                                {
                                                    await Control.SetDoBit(0, mc.MC_GPO, 2, 0);
                                                    GlobalStatus.Iscan = true;
                                                    GlobalStatus.ScanMesaage = ret.Item1;
                                                    GlobalStatus.IsXZeroBack = false;
                                                    GlobalStatus.IsYZeroBack = false;
                                                    GlobalStatus.IsZZeroBack = false;
                                                    GlobalStatus.IsEmergencyStop = true;
                                                    await Stop();
                                                }
                                            }
                                            else
                                            {
                                                Items.ElementAt(CurrentOriginalIndex - 1).Status = Status.Printting;
                                                CurrentOriginalIndex = Info.Originals.IndexOf(CurrentOriginal) + 1;
                                                await InvokeAsync(async () =>
                                                {
                                                    await Table.QueryAsync();
                                                });
                                                await CreateCardEx.Create(CurrentOriginal, MarkOption, PauseRestEvent, MarkOption.PhotoelectricitySetting.Height1 / MarkOption.XPluse.Value, MarkOption.PhotoelectricitySetting.Height2 / MarkOption.YPluse.Value);
                                                var isComplete = await CheckStatus();
                                                if (isComplete && !GlobalStatus.IsPause)
                                                {
                                                    await InvokeAsync(async () =>
                                                    {
                                                        await CrdStop();
                                                        StateHasChanged();
                                                    });
                                                    GlobalStatus.IsMarked = false;
                                                    PauseSource.Cancel();
                                                    await Control.SetDoBit(0, mc.MC_GPO, 11, 0);
                                                }
                                            }
                                        }
                                    }
                                }
                            }, TaskCreationOptions.LongRunning, FinishToken.Token);
                        }
                    }
                    else
                    {
                        await ToastService.Warning("提示", "桌面无玻璃");
                    }
                }
            }
        }
    }
}
